/**
 * Created by billy on 2020/12/21.
 */
//var _dir = __argv.name;
//var _date = g.time.formatTime(__time.startTime, "YYYY-MM-DD_hh_mm_ss");
//var _name = "";
//var _logFile = `${_date}.txt`;
//var _filePath = "";
//var _isCreated = {};
//var _firstLog = true;

//function log(...arg)
//{
//	if (!_isCreated)
//	{
//		createFile();
//	}
//
//	if (_firstLog)
//	{
//		g.fs.appendFileSync(_filePath, "\n");
//		_firstLog = false;
//	}
//
//	g.fs.appendFileSync(_filePath, arg.join(" "));
//}

//log.info = function (action, msg)
//{
//	if (!_isCreated)
//	{
//		createFile();
//	}
//
//	var info = `【${action}】${msg}\n`;
//	g.fs.appendFileSync(_filePath, info);
//}

//log.lastLogFile = function ()
//{
//	return _filePath;
//}

//log.init = function ($name)
//{
//	_name = $name;
//	_logFile = `${_date}-${_name}.txt`;
//}

var _logFileList = [];

//function createFile()
//{
//	g.file.createDirectory(_path("./log", _dir));
//	_filePath = _path("./log", _dir, _logFile);
//	if (!g.fs.existsSync(_filePath))
//	{
//		g.fs.writeFileSync(_filePath, getFileInfo());
//	}
//}

function getFileInfo()
{
	var startTime = __time.startTime;
	var startTimeStr = g.time.formatTime(startTime, "YYYY-MM-DD hh:mm:ss");
	var endTime = __time.startTime;
	var endTimeStr = g.time.formatTime(endTime, "YYYY-MM-DD hh:mm:ss");
	var param = __script.param.map(v=>"\"" + v[0] + "\":" + formatType(v[v.length - 1])).join(", ");

	var info =
		`【命令】sc ${getArgs().join(" ")}\n` +
		`【开始】${startTimeStr} (${startTime})\n` +
		`【结束】${endTimeStr} (${endTime})\n`
	!!param && (info += `【参数】{${param}}\n`);
//	info += "\n";

	return info;
}

function formatType($val)
{
	if (!isNum($val))
	{
		return `"${$val}"`;
	}

	return $val;
}

class LOG {
	constructor()
	{
		this._dir = __argv.name;
		this._date = g.time.formatTime(__time.startTime, "YYYY-MM-DD_hh_mm_ss");
		this._name = "";
		this._logFile = `${this._date}.txt`;
		this._filePath = "";
		this._isCreated = false;
		this._firstLog = true;
		this._currLog = "";
	}

	init($name)
	{
		this._name = $name;
		this._logFile = `${this._date}-${this._name}.txt`;
	}

	log(...arg)
	{
		if (!this._isCreated)
		{
			this.createFile();
		}

		if (this._firstLog)
		{
			g.fs.appendFileSync(this._filePath, "\n");
			this._firstLog = false;
			this._currLog += "\n";
		}

		var currLog = arg.join(" ");
		g.fs.appendFileSync(this._filePath, currLog);
		this._currLog += currLog;
	}

	info(action, msg)
	{
		if (!this._isCreated)
		{
			this.createFile();
		}

		var info = `【${action}】${msg}\n`;
		g.fs.appendFileSync(this._filePath, info);
		this._currLog += info;
	}

	async getLog($dirPath, $fileName = "*")
	{
		var dirPath = "";
		if (g.fs.existsSync($dirPath))
		{
			dirPath = $dirPath;
		}
		else
		{
			dirPath = _path("./log", $dirPath);
		}
		if ($dirPath.indexOf("*") > 0)
		{
			let pathObj = g.path.parse($dirPath);
			$dirPath = pathObj.dir;
			$fileName = pathObj.base;
			dirPath = _path("./log", $dirPath);
		}
		else
		{
			if (!g.fs.existsSync(dirPath))
			{
				__exit.error("Directory no found: " + dirPath);
			}

			var stat = g.fs.statSync(_path("./log", $dirPath));
			if (!stat.isDirectory())
			{
				let pathObj = g.path.parse($dirPath);
				$dirPath = pathObj.dir;
				$fileName = pathObj.base;
				dirPath = _path("./log", $dirPath);
			}
		}
//	trace(dirPath)
//	trace($dirPath)
//	trace($fileName)
		if (!g.fs.existsSync(dirPath))
		{
			__exit.error("Directory no found: " + dirPath);
		}

		var filePath = "";
		if ($fileName.indexOf("*") >= 0)
		{
			$fileName = $fileName.replace(/\./g, "\\.").replace(/\*/g, ".+?");
			var reg = new RegExp($fileName, "g");
			var logList = g.file.getDirectoryAllListing(dirPath);
			var fileList = [];
			logList = logList.forEach(v=>
			{
				var fileName = g.path.parse(v).base;
				var matchs = fileName.match(reg);
//			console.log(fileName, reg, matchs)
				if (matchs && matchs.length > 0)
				{
					fileList.push({
						path: v,
						name: fileName,
						time: g.fs.statSync(v).atime.getTime()
					})
				}
			})

			if (fileList.length == 0)
			{
				__exit.error("File no found: " + $fileName);
			}
			fileList.sort((a, b)=>b.time - a.time);
			filePath = fileList[0].path;
		}
		else
		{
			filePath = g.path.join(dirPath, $fileName);
			if (!g.fs.existsSync(filePath))
			{
				__exit.error("File no found: " + filePath);
			}
		}

//	trace(filePath);
		__time.pause();
		var answer = await require("inquirer").prompt([{
			type: "confirm",
			name: "value",
			message: "【Is this File for you?】" + filePath.replace(_path(""), ""),
			default: false,
		}])

		__time.resume();
		if (answer.value)
		{
			this.info("getLog", filePath);
			var logFileContent = g.fs.readFileSync(filePath).toString();
			logFileContent = logFileContent.split("\n");
			var headInfo = {};
			while (true)
			{
				if (logFileContent[0] == "")
				{
					__merge(headInfo, getHeadInfo(logFileContent.shift()));
					break;
				}

				__merge(headInfo, getHeadInfo(logFileContent.shift()));
			}
			return {
				list: logFileContent.map(v=>
				{
					v = v.replace(/\t/g, " ").split(" ");
					return v[v.length - 1];
				}),
				info: headInfo
			};
		}
		__exit();
	}

	createFile()
	{
		g.file.createDirectory(_path("./log", this._dir));
		this._filePath = _path("./log", this._dir, this._logFile);
		if (!g.fs.existsSync(this._filePath))
		{
			_logFileList.push(this._filePath);
			var currLog = getFileInfo();
			g.fs.writeFileSync(this._filePath, currLog);
			this._currLog = currLog;
		}
	}

	get date()
	{
		return this._date;
	}

	get dir()
	{
		return this._dir;
	}

	get currLog()
	{
		return this._currLog;
	}
}

function getHeadInfo($content)
{
	var index = $content.indexOf("】");
	var type = $content.substring($content.indexOf("【") + 1, index)
	if (type == "命令")
	{
		return {cmd: $content.substring(index + 1)};
	}
	else if (type == "开始")
	{
		return {startTime: $content.substring($content.indexOf("(") + 1, $content.indexOf(")")) - 0};
	}
	else if (type == "结束")
	{
		return {endTime: $content.substring($content.indexOf("(") + 1, $content.indexOf(")")) - 0};
	}
	else if (type == "参数")
	{
		return {param: JSON.parse($content.substring(index + 1))};
	}
	return {};
}

module.exports = {
	get: function ()
	{
		var logInstance = new LOG();

		var xlog = function (...arg)
		{
			logInstance.log.apply(logInstance, arg);
		}
		xlog.init = logInstance.init.bind(logInstance);
		xlog.info = logInstance.info.bind(logInstance);
		xlog.getLog = logInstance.getLog.bind(logInstance);
		defineProperty(xlog, "date", function ()
		{
			return logInstance.date;
		})
		defineProperty(xlog, "dir", function ()
		{
			return logInstance.dir;
		})
		defineProperty(xlog, "currLog", function ()
		{
			return logInstance.currLog;
		})
		return xlog;
	},
	logFile: _logFileList
}